package com.zhbcm.netty.client;

import com.zhbcm.netty.handler.ClientHandler;
import com.zhbcm.netty.po.RpcRequest;
import com.zhbcm.netty.po.RpcResponse;
import com.zhbcm.netty.utils.RpcDecoder;
import com.zhbcm.netty.utils.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/4/22 22:54
 */
public class NettyClient
{
    private final String host;
    private final int port;
    private Channel channel;

    public NettyClient(String host, int port)
    {
        this.host = host;
        this.port = port;
    }

    public void start() throws InterruptedException
    {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                // 使用NioSocketChannel来作为连接用的channel类
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>()
                {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception
                    {
                        System.out.println("正在连接中...");
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class)); //编码request
                        pipeline.addLast(new RpcDecoder(RpcResponse.class)); //解码response
                        pipeline.addLast(new ClientHandler()); //客户端处理类
                    }
                });
        //发起异步连接请求，绑定连接端口和host信息
        final ChannelFuture future = b.connect(host, port).sync();
        future.addListener(new ChannelFutureListener()
        {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception
            {
                if (future.isSuccess())
                {
                    System.out.println("连接服务器成功");

                } else
                {
                    System.out.println("连接服务器失败");
                    future.cause().printStackTrace();
                    group.shutdownGracefully(); //关闭线程组
                }
            }
        });
        this.channel = future.channel();
    }

    public Channel getChannel()
    {
        return channel;
    }
}
